import { bootstrap } from './server';
import { logger } from './logger'
import cluster, { Worker } from 'cluster'
import { init } from "./init";
export const WORKERS = new Map<number, Worker>()
export const WORKERPIDS = new Map<number, number>()
export const main = () => {
    const parsedArgs = init()
    if (cluster.isPrimary) {
        cluster.on('listening', (work, address) => {
            logger.info(`server is running at ${parsedArgs.dev ? 'dev' : 'prod'} on ${work.process.pid} ${address.address}:${address.port}`)
        })
        cluster.on('exit', (worker, code, signal) => {
            const childNo = WORKERPIDS.get(worker.process.pid)
            const item = cluster.fork({
                'child_no': childNo
            })
            WORKERS.set(childNo, item)
            WORKERPIDS.set(item.process.pid, childNo)
        })
        for (let i = 0; i < parsedArgs.cpus; i++) {
            const childNo = i + 1
            const worker = cluster.fork({
                'child_no': childNo
            })
            WORKERS.set(childNo, worker)
            WORKERPIDS.set(worker.process.pid, childNo)
        }
        process.on('SIGTERM', () => {
            WORKERS.forEach(it => {
                process.kill(it.process.pid)
            })
            process.exit(0)
        })
    } else {
        bootstrap(parsedArgs)
    }
}
